package liuds.music;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import liuds.music.adapter.MainPagerAdapter;
import liuds.music.adapter.PlayMusicAdapter;
import liuds.music.model.MediaService;
import liuds.music.model.Music;
import liuds.music.model.NetWorkStateReceiver;
import liuds.music.utils.MusicUtils;
import liuds.music.utils.Utils;
import liuds.music.view.CellView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,DrawerLayout.DrawerListener {

    private final int SEARCH_CODE = 1;

    private DrawerLayout drawerLayout;
    private RelativeLayout setting,exit;

    private Toolbar toolbar;
    private LinearLayout tabLayout;

    private ViewPager mainPager;

    private MusicFragment musicFragment;
    private RecyclerView playListView;
    public ImageButton play,playType;

    public MediaService mediaService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        App.addActivity(this);

        initView();

        initListener();
    }

    private void initView() {
        drawerLayout = findViewById(R.id.drawerLayout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        drawerLayout.addDrawerListener(this);
        toggle.syncState();
        StatusBarUtil.setColorForDrawerLayout(this, drawerLayout, getResources().getColor(R.color.colorPrimary),0);

        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.menu);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        setting = findViewById(R.id.setting);
        exit = findViewById(R.id.exit);
        setting.setOnClickListener(this);
        exit.setOnClickListener(this);

        tabLayout = findViewById(R.id.tabLayout);
        for(int i=0;i<tabLayout.getChildCount();i++){
            tabLayout.getChildAt(i).setTag(i);
            tabLayout.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mainPager.setCurrentItem((int)v.getTag());
                }
            });
        }


        final Snackbar snackbar = Snackbar.make(toolbar,"无网络连接",Snackbar.LENGTH_INDEFINITE);
        snackbar.setAction("关闭", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snackbar.dismiss();
            }
        });
        NetWorkStateReceiver receiver = new NetWorkStateReceiver(new NetWorkStateReceiver.OnNetWorkChangeListener() {

            @Override
            public void onDisconnect() {
                snackbar.show();
            }

            @Override
            public void onConnect() {
                snackbar.dismiss();
            }
        });
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);//注册

        serviceIntent = new Intent(MainActivity.this,MediaService.class);
        Intent mediaIntent = new Intent(this,MediaService.class);
        bindService(mediaIntent,MediaServiceConnection,BIND_AUTO_CREATE);

        mainPager = findViewById(R.id.mainPager);
        List<BaseFragment> fragments = new ArrayList<>();
        musicFragment = new MusicFragment("音乐");
        fragments.add(musicFragment);
        fragments.add(new NewsFragment("新闻"));
        fragments.add(new TestFragment("测试"));
        MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager(),fragments);
        adapter.showTitle(false);
        mainPager.setAdapter(adapter);
        mainPager.setOffscreenPageLimit(3);

        mainPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                if(position >= tabLayout.getTabCount()-1){
//                    if(positionOffsetPixels<(App.screenWidth/2)){
//                        setSelectedTabIcon(position);
//                    }else{
//                        setSelectedTabIcon(position-1);
//                    }
//                }else{
//                    if(positionOffsetPixels>(App.screenWidth/2)){
//                        setSelectedTabIcon(position+1);
//                    }else{
//                        setSelectedTabIcon(position);
//                    }
//                }
            }

            @Override
            public void onPageSelected(int position) {
                for(int i=0;i<tabLayout.getChildCount();i++){
                    if(position == i){
                        tabLayout.getChildAt(position).setSelected(true);
                    }else{
                        tabLayout.getChildAt(i).setSelected(false);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.getChildAt(0).setSelected(true);

        playListView = findViewById(R.id.playListView);
        playMusicLayoutManager = new LinearLayoutManager(MainActivity.this,LinearLayoutManager.HORIZONTAL,false);//reverselayout是否反转的意思
        playListView.setLayoutManager(playMusicLayoutManager);
        setPlayMusicListAdapter();

        play = findViewById(R.id.play);
        playType = findViewById(R.id.playType);
        setPlayType();
    }

    private LinearLayoutManager playMusicLayoutManager;
    private PlayMusicAdapter playMusicAdapter;
    private void setPlayMusicListAdapter(){
        if (playMusicAdapter == null){
            playMusicAdapter = new PlayMusicAdapter(this,MusicUtils.getPlayMusicList());
            playListView.setAdapter(playMusicAdapter);
            playListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if(newState == 0){
                        if(MusicUtils.getPlayIndex() != playMusicLayoutManager.findFirstVisibleItemPosition()){
                            playMusic(MusicUtils.getPlayMusicList().get(playMusicLayoutManager.findFirstVisibleItemPosition()).getId());
                        }
                    }
                }
            });
            PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
            pagerSnapHelper.attachToRecyclerView(playListView);
            playMusicLayoutManager.scrollToPosition(MusicUtils.getPlayIndex());
        }else{
            if(MusicUtils.playMusicList.size() <=0 ) return;
            int id = MusicUtils.getPlayMusicList().get(MusicUtils.getPlayIndex()).getId();
            MusicUtils.playMusicList = null;
            playMusicAdapter.music = MusicUtils.getPlayMusicList();
            for(int i=0;i<MusicUtils.getPlayMusicList().size();i++){
                if(MusicUtils.getPlayMusicList().get(i).getId() == id){
                    MusicUtils.setPlayIndex(i);
                    playMusicLayoutManager.scrollToPosition(i);
                    break;
                }
            }
        }
    }



    private void initListener() {
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playMusic(MusicUtils.getPlayMusicList().get(MusicUtils.getPlayIndex()).getId());
            }
        });

        playType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (MusicUtils.getPlayType()){
                    case ORDERLY:
                        playType.setImageResource(R.mipmap.type_circulation);
                        MusicUtils.setPlayType(MusicUtils.PlayType.CIRCULATION);
                        Utils.toast("单曲循环");
                        break;
                    case CIRCULATION:
                        playType.setImageResource(R.mipmap.type_random);
                        MusicUtils.setPlayType(MusicUtils.PlayType.RANDOM);
                        Utils.toast("随机播放");
                        setPlayMusicListAdapter();
                        break;
                    case RANDOM:
                        playType.setImageResource(R.mipmap.type_orderly);
                        MusicUtils.setPlayType(MusicUtils.PlayType.ORDERLY);
                        Utils.toast("列表循环");
                        setPlayMusicListAdapter();
                        break;
                }
            }
        });
    }

    public void playMusic(int id){
        if(MusicUtils.playMusicList.size() <=0 ) return;

        int index=0;
        for(int i=0;i<MusicUtils.getPlayMusicList().size();i++){
            if(MusicUtils.getPlayMusicList().get(i).getId() == id){
                index = i;
            }
        }

        serviceIntent.putExtra("index",index);
        startService(serviceIntent);
        musicFragment.musicAdapter.setCurrentPlayIndex(index);
        playMusicLayoutManager.scrollToPosition(index);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.search:
                Intent intent = new Intent(this,SearchActivity.class);
                startActivityForResult(intent,SEARCH_CODE);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==SEARCH_CODE && resultCode==RESULT_OK){
            Bundle bundle = data.getExtras();
            if(bundle!=null){
                playMusic(MusicUtils.getPlayMusicList().get(bundle.getInt("index")).getId());
            }
        }
    }

    @Override
    public void onBackPressed() {
        //判断用户是否点击了“返回键”
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
        }
    }

    public void setPlayType(){
        MusicUtils.PlayType playType = MusicUtils.getPlayType();
        switch (playType){
            case ORDERLY:
                this.playType.setImageResource(R.mipmap.type_orderly);
                break;
            case CIRCULATION:
                this.playType.setImageResource(R.mipmap.type_circulation);
                break;
            case RANDOM:
                this.playType.setImageResource(R.mipmap.type_random);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(MediaServiceConnection);
        super.onDestroy();
    }

    private Intent serviceIntent;

    private ServiceConnection MediaServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MediaService.MediaBinder mediaBinder = (MediaService.MediaBinder) service;

            mediaService = mediaBinder.getMediaService(new MediaService.OnMediaPlayerStateChangeListener() {
                @Override
                public void onStart() {
                    play.setImageResource(R.mipmap.pause);
                }

                @Override
                public void onPause() {
                    play.setImageResource(R.mipmap.play);
                }

                @Override
                public void onPlayCompletion() {
                    if(MusicUtils.getPlayType()== MusicUtils.PlayType.CIRCULATION){
                        playMusic(MusicUtils.getPlayMusicList().get(MusicUtils.getPlayIndex()).getId());
                    }else{
                        if(MusicUtils.getPlayIndex() >= MusicUtils.getPlayMusicList().size()-1){
                            setPlayMusicListAdapter();
                            playMusic(MusicUtils.getPlayMusicList().get(0).getId());
                        }else{
                            playMusic(MusicUtils.getPlayMusicList().get((MusicUtils.getPlayIndex()+1)).getId());
                        }
                    }

                }
            });
            if(mediaService.mediaPlayer.isPlaying()){
                play.setImageResource(R.mipmap.pause);
            }else{
                play.setImageResource(R.mipmap.play);
            }
            App.log("Service与Activity已连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    private View clickView;
    @Override
    public void onClick(final View v) {
        if(v.getId() == R.id.exit){
            App.exit();
        }else{
            drawerLayout.closeDrawer(Gravity.START);
            clickView = v;
        }
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }

    @Override
    public void onDrawerOpened(View drawerView) {

    }

    @Override
    public void onDrawerClosed(View drawerView) {
        if(clickView != null){
            switch (clickView.getId()){
                case R.id.setting:{
                    Intent intent = new Intent(MainActivity.this,SettingActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.about:{
                    Utils.toast(getString(R.string.about));
                    break;
                }
                case R.id.avatar:{
                    Intent intent = new Intent(MainActivity.this,UserActivity.class);
                    startActivity(intent);
                    break;
                }
                case R.id.nightTheme:{
                    Utils.toast(getString(R.string.night));
                    break;
                }
                case R.id.changeTheme:{
                    Utils.toast(getString(R.string.changeTheme));
                    break;
                }
                case R.id.timingPlay:{
                    Utils.toast(getString(R.string.timingPlay));
                    break;
                }
                case R.id.scan:{
                    Utils.toast("扫一扫");
                    break;
                }
            }
            clickView = null;
        }
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }
}



